package com.admin.rxandroidtest.rxAndroid;

import android.view.View;

import com.admin.rxandroidtest.BaseViewActivity;

import java.util.Arrays;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Cancellable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class RxAndroidActivity extends BaseViewActivity {

    private List<String> msl= Arrays.asList(new String[]{"2", "1","dsd","frerfew","ff","wqssaaw","qwed","ddfadd"});
    private Disposable disposable;
    private int index=0;
    @Override
    public void initEvent() {

    }

    @Override
    protected void onStart() {
        super.onStart();
        Observable<Integer> ser=getButton();
        disposable=ser.observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        //可修改UI也可什么也不做
                        //也可以不用此 doOnNext
                        pb1.setVisibility(View.VISIBLE);
                    }
                })
                .observeOn(Schedulers.io())
                .map(new Function<Integer, Integer>() {
                    @Override
                    public Integer apply(Integer integer) throws Exception {
                        //通常此处为一个耗时操作，例如一个大量数据的筛选等
                        return (++index)%msl.size();
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer s) throws Exception {
                        tv1.setText(s+"");
                        tvr.setText(msl.get(s));
                        pb1.setVisibility(View.GONE);
                    }
                });

    }

    private Observable<Integer> getButton(){
        return Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(final ObservableEmitter<Integer> e) throws Exception {
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        e.onNext(index);
                    }
                });
                e.setCancellable(new Cancellable() {
                    @Override
                    public void cancel() throws Exception {
                        btn.setOnClickListener(null);
                    }
                });
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!disposable.isDisposed()){
            disposable.dispose();
        }
    }

}
